#encoding=utf-8
from bottle import request, redirect
from google.appengine.api import users
from model import Article, Category, Comment, Tag
import re
import urllib2

page_size = 9

def articlesByCreateDate():
    articles = Article.all()
    date = {}
    for art in articles:
        d = art.create_date.strftime("%Y年%m月")
        if date.has_key(d):
            date[d] = date[d] + 1
        else:
            date[d] = 1
    return date

def allcate():
    categories = Category.all()
    cates = []
    for cate in categories:
        cnt = Article.gql("where category_id = :1", cate.id).count()
        setattr(cate, "art_cnt", cnt)
        cates.append(cate)
    categories = cates
    return categories

def alltags():
    tags = Tag.all()
    result = {}
    for tag in tags:
        if result.has_key(tag.val):
            result[tag.val] = result[tag.val] + 1
        else:
            result[tag.val] = 1
    return result

def convertArticle(article):
    cate = Category.gql("where id = :1", int(article.category_id)).get()
    setattr(article, 'cate_name', cate.cate_name)
    cnt = Comment.gql('where art_id =:1', article.id).count()
    setattr(article, 'comment_cnt', cnt)
    tags = Tag.gql("where art_id = :1", article.id)
    setattr(article, "tags", [item for item in tags])
    return article
    
def artilceByComments():
    queryComments = Comment.all()
    artIds = {}
    for comments in queryComments:
        if artIds.has_key(comments.art_id):
            artIds[comments.art_id] = artIds[comments.art_id] + 1
        else:
            artIds[comments.art_id] = 1
    artIdsSorted = [k for k, v in sorted(artIds.items(), key=lambda x: x[1], reverse=True)]
    return [Article.gql("where id = :1", id).get() for id in artIdsSorted]

def decode_param (func):
    def wrapper (*args, **kwargs):
        for param in kwargs:
            kwargs[param] = urllib2.unquote(kwargs[param]).decode("utf-8")
        return func(*args, **kwargs)
    return wrapper

def decode_post_param (func):
    def wrapper (*args, **kwargs):
        for param in request.forms:
            kwargs[param] = urllib2.unquote(request.forms[param]).decode("utf-8")
        return func(*args, **kwargs)
    return wrapper

def login_required (url):
    def decorator(func):
        def wrapper (*args, **kwargs):
            if(users.is_current_user_admin()):
                return func(*args, **kwargs)
            else:
                urls = url.split('/')
                new_url = []
                for t in urls:
                    if t.find(':') != -1:
                        t = kwargs[t[1:len(t)]]
                    new_url.append(t)
                redirect(create_login_url("/".join(new_url)))
        return wrapper
    return decorator

def syntaxhighlighter(str):
    p = re.compile('\[code\s*(?:=\s*((?:(?!")[\s\S])+?)(?:"[\s\S]*?)?)?\]([\s\S]*?)\[\/code\]', re.IGNORECASE)
    for m in p.finditer(str):
        str = p.sub('<pre class="brush:%s;">%s</pre>' % (m.groups()[0], m.groups()[1]), str)
    return str
    
def check_login():
    #user = users.get_current_user()
    return users.is_current_user_admin()

def create_login_url(redirect_url):
    return users.create_login_url(redirect_url)

def create_logout_url(redirect_url):
    return users.create_logout_url(redirect_url)

